package org.crud4j.validator;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class MethodValidator<T> implements BeanValidator<T> {

	private static Object[] params = new Object[0];

	private String name;

	private ValueValidator valueValidator;

	private Method method;

	@SuppressWarnings("unchecked")
	public MethodValidator(Method method, ValueValidator validator) {
		super();
		this.method = method;

		if (method.getName().startsWith("get") && method.getName().length() > 3) {
			this.name = method.getName().substring(3);
		} else {
			this.name = method.getName();
		}

		this.valueValidator = validator;
	}

	public void validate(T bean) throws BeanValidatorException {
		try {
			Object value = this.method.invoke(bean, params);
			this.valueValidator.validate(value);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (InvocationTargetException e) {
			throw new RuntimeException(e);
		} catch (ValueValidatorException e) {
			throw new BeanValidatorException(bean, new ValidationResult(
					this.name, e));
		}
	}

}
